package com.zlx.store.goods.job;

import com.zlx.store.domain.entity.Goods;
import com.zlx.store.goods.dao.GoodsDao;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 自动化临期商品
 */
public class ExpiredGoodsJob extends QuartzJobBean {
    @Autowired
    GoodsDao goodsDao;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        // 获取当前日期
        Date currentDate = new Date();
        // 查询数据库获取所有商品列表
        List<Goods> goodsList = goodsDao.selectList(null);
        // 筛选保质期不足 5 分之一的商品
        for (Goods goods : goodsList) {
            if (Objects.nonNull(goods.getGoodsShelfLife())) {
                if (Objects.nonNull(goods.getGoodsExpirationTime())){
                Integer life = goods.getGoodsShelfLife() / 5;
                Date standardDate = new Date(currentDate.getTime() + life * 24 * 60 * 60 * 1000);
                // 添加查询条件：保质期不足 5 分之一的商品
                if (goods.getGoodsExpirationTime().before(standardDate)) {
                    Long expirationTimestamp = goods.getGoodsExpirationTime().getTime();
                    redisTemplate.opsForZSet().add("expiredGoods", goods.getGoodsId(), expirationTimestamp);
                }
            }
        }
        }
    }
}
